Artificial Intelligence Nanodegree

Computer Vision Capstone

Project: Facial Keypoint Detection


Welcome to the final Computer Vision project in the Artificial Intelligence Nanodegree program!

In this project, you’ll combine your knowledge of computer vision techniques and deep learning to build and end-to-end facial keypoint recognition system! Facial keypoints include points around the eyes, nose, and mouth on any face and are used in many applications, from facial tracking to emotion recognition.

There are three main parts to this project:

Part 1 : Investigating OpenCV, pre-processing, and face detection

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!


*Here's what you need to know to complete the project:

  1. In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested.

    a. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

  1. In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation.

    a. Each section where you will answer a question is preceded by a 'Question X' header.

    b. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional suggestions for enhancing the project beyond the minimum requirements. If you decide to pursue the "(Optional)" sections, you should include the code in this IPython notebook.

Your project submission will be evaluated based on your answers to each of the questions and the code implementations you provide.

Steps to Complete the Project

Each part of the notebook is further broken down into separate steps. Feel free to use the links below to navigate the notebook.

In this project you will get to explore a few of the many computer vision algorithms built into the OpenCV library. This expansive computer vision library is now almost 20 years old and still growing!

The project itself is broken down into three large parts, then even further into separate steps. Make sure to read through each step, and complete any sections that begin with '(IMPLEMENTATION)' in the header; these implementation sections may contain multiple TODOs that will be marked in code. For convenience, we provide links to each of these steps below.

Part 1 : Investigating OpenCV, pre-processing, and face detection

  • Step 0: Detect Faces Using a Haar Cascade Classifier
  • Step 1: Add Eye Detection
  • Step 2: De-noise an Image for Better Face Detection
  • Step 3: Blur an Image and Perform Edge Detection
  • Step 4: Automatically Hide the Identity of an Individual

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

  • Step 5: Create a CNN to Recognize Facial Keypoints
  • Step 6: Compile and Train the Model
  • Step 7: Visualize the Loss and Answer Questions

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!

  • Step 8: Build a Robust Facial Keypoints Detector (Complete the CV Pipeline)

Step 0: Detect Faces Using a Haar Cascade Classifier

Have you ever wondered how Facebook automatically tags images with your friends' faces? Or how high-end cameras automatically find and focus on a certain person's face? Applications like these depend heavily on the machine learning task known as face detection - which is the task of automatically finding faces in images containing people.

At its root face detection is a classification problem - that is a problem of distinguishing between distinct classes of things. With face detection these distinct classes are 1) images of human faces and 2) everything else.

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the detector_architectures directory.

Import Resources

In the next python cell, we load in the required libraries for this section of the project.

In [1]:
# Import required libraries for this section

%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
import math
import cv2                     # OpenCV library for computer vision
from PIL import Image
import time 

Next, we load in and display a test image for performing face detection.

Note: by default OpenCV assumes the ordering of our image's color channels are Blue, then Green, then Red. This is slightly out of order with most image types we'll use in these experiments, whose color channels are ordered Red, then Green, then Blue. In order to switch the Blue and Red channels of our test image around we will use OpenCV's cvtColor function, which you can read more about by checking out some of its documentation located here. This is a general utility function that can do other transformations too like converting a color image to grayscale, and transforming a standard color image to HSV color space.

In [2]:
# Load in color image for face detection
image = cv2.imread('images/test_image_1.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot our image using subplots to specify a size and title
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[2]:
<matplotlib.image.AxesImage at 0x11954da20>

There are a lot of people - and faces - in this picture. 13 faces to be exact! In the next code cell, we demonstrate how to use a Haar Cascade classifier to detect all the faces in this test image.

This face detector uses information about patterns of intensity in an image to reliably detect faces under varying light conditions. So, to use this face detector, we'll first convert the image from color to grayscale.

Then, we load in the fully trained architecture of the face detector -- found in the file haarcascade_frontalface_default.xml - and use it on our image to find faces!

To learn more about the parameters of the detector see this post.

In [3]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 13
Out[3]:
<matplotlib.image.AxesImage at 0x12074a978>

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.


Step 1: Add Eye Detections

There are other pre-trained detectors available that use a Haar Cascade Classifier - including full human body detectors, license plate detectors, and more. A full list of the pre-trained architectures can be found here.

To test your eye detector, we'll first read in a new test image with just a single face.

In [4]:
# Load in color image for face detection
image = cv2.imread('images/james.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot the RGB image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[4]:
<matplotlib.image.AxesImage at 0x1206a8710>

Notice that even though the image is a black and white image, we have read it in as a color image and so it will still need to be converted to grayscale in order to perform the most accurate face detection.

So, the next steps will be to convert this image to grayscale, then load OpenCV's face detector and run it with parameters that detect this face accurately.

In [5]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.25, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detection')
ax1.imshow(image_with_detections)
Number of faces detected: 1
Out[5]:
<matplotlib.image.AxesImage at 0x123abfbe0>

(IMPLEMENTATION) Add an eye detector to the current face detection setup.

A Haar-cascade eye detector can be included in the same way that the face detector was and, in this first task, it will be your job to do just this.

To set up an eye detector, use the stored parameters of the eye cascade detector, called haarcascade_eye.xml, located in the detector_architectures subdirectory. In the next code cell, create your eye detector and store its detections.

A few notes before you get started:

First, make sure to give your loaded eye detector the variable name

eye_cascade

and give the list of eye regions you detect the variable name

eyes

Second, since we've already run the face detector over this image, you should only search for eyes within the rectangular face regions detected in faces. This will minimize false detections.

Lastly, once you've run your eye detector over the facial detection region, you should display the RGB image with both the face detection boxes (in red) and your eye detections (in green) to verify that everything works as expected.

In [18]:
# Make a copy of the original image to plot rectangle detections
image_with_detections = np.copy(image)   

# Loop over the detections and draw their corresponding face detection boxes
for (x,y,w,h) in faces:
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h),(255,0,0), 3)
    
# Do not change the code above this comment!

    
## TODO: Add eye detection, using haarcascade_eye.xml, to the current face detector algorithm
## TODO: Loop over the eye detections and draw their corresponding boxes in green on image_with_detections
eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')
#eyes = eye_cascade.detectMultiScale(gray, 1.1, 6)
#for (x,y,w,h) in eyes:
#    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h),(0,255,0), 2)
for (x,y,w,h) in faces:
    eyes = eye_cascade.detectMultiScale(gray[y:y+h,x:x+w], 1.1, 6)
    for (eye_x,eye_y,eye_w,eye_h) in eyes:
        cv2.rectangle(image_with_detections, (x+eye_x,y+eye_y), (x+eye_x+eye_w,y+eye_y+eye_h), (0,255,0), 2)

# Plot the image with both faces and eyes detected
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face and Eye Detection')
ax1.imshow(image_with_detections)
Out[18]:
<matplotlib.image.AxesImage at 0x11e6d4860>

(Optional) Add face and eye detection to your laptop camera

It's time to kick it up a notch, and add face and eye detection to your laptop's camera! Afterwards, you'll be able to show off your creation like in the gif shown below - made with a completed version of the code!

Notice that not all of the detections here are perfect - and your result need not be perfect either. You should spend a small amount of time tuning the parameters of your detectors to get reasonable results, but don't hold out for perfection. If we wanted perfection we'd need to spend a ton of time tuning the parameters of each detector, cleaning up the input image frames, etc. You can think of this as more of a rapid prototype.

The next cell contains code for a wrapper function called laptop_camera_face_eye_detector that, when called, will activate your laptop's camera. You will place the relevant face and eye detection code in this wrapper function to implement face/eye detection and mark those detections on each image frame that your camera captures.

Before adding anything to the function, you can run it to get an idea of how it works - a small window should pop up showing you the live feed from your camera; you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [47]:
### Add face and eye detection to this laptop camera function 
# Make sure to draw out all faces/eyes found in each frame on the shown video feed

import cv2
import time 
import numpy

# wrapper function for face/eye detection with your laptop camera
def laptop_camera_go():
    # Define feature cascades we want
    face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
    eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')
    
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep the video stream open
    while rval:
        # Turn image into gray scale
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        
        # Detect faces
        faces = face_cascade.detectMultiScale(gray, 1.08, 8)
        for (x,y,w,h) in faces:
            # Draw faces
            frame = cv2.rectangle(frame, (x,y), (x+w,y+h), (255,0,0), 3)
            # Detect eyes within the face
            eyes = eye_cascade.detectMultiScale(gray[y:y+h,x:x+w], 1.1, 6)
            for (eye_x,eye_y,eye_w,eye_h) in eyes:
                frame = cv2.rectangle(frame, (x+eye_x,y+eye_y), (x+eye_x+eye_w,y+eye_y+eye_h), (0,255,0), 2)
        
        # Plot the image from camera with all the face and eye detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            # Make sure window closes on OSx
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.0)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
In [48]:
# Call the laptop camera face/eye detector function above
laptop_camera_go()

Step 2: De-noise an Image for Better Face Detection

Image quality is an important aspect of any computer vision task. Typically, when creating a set of images to train a deep learning network, significant care is taken to ensure that training images are free of visual noise or artifacts that hinder object detection. While computer vision algorithms - like a face detector - are typically trained on 'nice' data such as this, new test data doesn't always look so nice!

When applying a trained computer vision algorithm to a new piece of test data one often cleans it up first before feeding it in. This sort of cleaning - referred to as pre-processing - can include a number of cleaning phases like blurring, de-noising, color transformations, etc., and many of these tasks can be accomplished using OpenCV.

In this short subsection we explore OpenCV's noise-removal functionality to see how we can clean up a noisy image, which we then feed into our trained face detector.

Create a noisy image to work with

In the next cell, we create an artificial noisy version of the previous multi-face image. This is a little exaggerated - we don't typically get images that are this noisy - but image noise, or 'grainy-ness' in a digitial image - is a fairly common phenomenon.

In [44]:
# Load in the multi-face test image again
image = cv2.imread('images/test_image_1.jpg')

# Convert the image copy to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Make an array copy of this image
image_with_noise = np.asarray(image)

# Create noise - here we add noise sampled randomly from a Gaussian distribution: a common model for noise
noise_level = 40
noise = np.random.randn(image.shape[0],image.shape[1],image.shape[2])*noise_level

# Add this noise to the array image copy
image_with_noise = image_with_noise + noise

# Convert back to uint8 format
image_with_noise = np.asarray([np.uint8(np.clip(i,0,255)) for i in image_with_noise])

# Plot our noisy image!
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image')
ax1.imshow(image_with_noise)
Out[44]:
<matplotlib.image.AxesImage at 0x134c32320>

In the context of face detection, the problem with an image like this is that - due to noise - we may miss some faces or get false detections.

In the next cell we apply the same trained OpenCV detector with the same settings as before, to see what sort of detections we get.

In [45]:
# Convert the RGB  image to grayscale
gray_noise = cv2.cvtColor(image_with_noise, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_noise, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image_with_noise)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 12
Out[45]:
<matplotlib.image.AxesImage at 0x134c32358>

With this added noise we now miss one of the faces!

(IMPLEMENTATION) De-noise this image for better face detection

Time to get your hands dirty: using OpenCV's built in color image de-noising functionality called fastNlMeansDenoisingColored - de-noise this image enough so that all the faces in the image are properly detected. Once you have cleaned the image in the next cell, use the cell that follows to run our trained face detector over the cleaned image to check out its detections.

You can find its official documentation here and a useful example here.

Note: you can keep all parameters except photo_render fixed as shown in the second link above. Play around with the value of this parameter - see how it affects the resulting cleaned image.

In [46]:
## TODO: Use OpenCV's built in color image de-noising function to clean up our noisy image!
denoised_image = cv2.fastNlMeansDenoisingColored(image_with_noise, None, h=20, hColor=0, templateWindowSize=7, searchWindowSize=21)
In [43]:
## TODO: Run the face detector on the de-noised image to improve your detections and display the result
# Convert the RGB  image to grayscale
gray_denoised = cv2.cvtColor(denoised_image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_denoised, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(denoised_image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Denoised Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 13
Out[43]:
<matplotlib.image.AxesImage at 0x134c9c080>

Step 3: Blur an Image and Perform Edge Detection

Now that we have developed a simple pipeline for detecting faces using OpenCV - let's start playing around with a few fun things we can do with all those detected faces!

Importance of Blur in Edge Detection

Edge detection is a concept that pops up almost everywhere in computer vision applications, as edge-based features (as well as features built on top of edges) are often some of the best features for e.g., object detection and recognition problems.

Edge detection is a dimension reduction technique - by keeping only the edges of an image we get to throw away a lot of non-discriminating information. And typically the most useful kind of edge-detection is one that preserves only the important, global structures (ignoring local structures that aren't very discriminative). So removing local structures / retaining global structures is a crucial pre-processing step to performing edge detection in an image, and blurring can do just that.

Below is an animated gif showing the result of an edge-detected cat taken from Wikipedia, where the image is gradually blurred more and more prior to edge detection. When the animation begins you can't quite make out what it's a picture of, but as the animation evolves and local structures are removed via blurring the cat becomes visible in the edge-detected image.

Edge detection is a convolution performed on the image itself, and you can read about Canny edge detection on this OpenCV documentation page.

Canny edge detection

In the cell below we load in a test image, then apply Canny edge detection on it. The original image is shown on the left panel of the figure, while the edge-detected version of the image is shown on the right. Notice how the result looks very busy - there are too many little details preserved in the image before it is sent to the edge detector. When applied in computer vision applications, edge detection should preserve global structure; doing away with local structures that don't help describe what objects are in the image.

In [12]:
# Load in the image
image = cv2.imread('images/fawzia.jpg')

# Convert to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)  

# Perform Canny edge detection
edges = cv2.Canny(gray,100,200)

# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)

# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Canny Edges')
ax2.imshow(edges, cmap='gray')
Out[12]:
<matplotlib.image.AxesImage at 0x7fe730063240>

Without first blurring the image, and removing small, local structures, a lot of irrelevant edge content gets picked up and amplified by the detector (as shown in the right panel above).

(IMPLEMENTATION) Blur the image then perform edge detection

In the next cell, you will repeat this experiment - blurring the image first to remove these local structures, so that only the important boudnary details remain in the edge-detected image.

Blur the image by using OpenCV's filter2d functionality - which is discussed in this documentation page - and use an averaging kernel of width equal to 4.

In [13]:
### TODO: Blur the test imageusing OpenCV's filter2d functionality, 
# Use an averaging kernel, and a kernel width equal to 4
blurred_image = cv2.blur(image,(4,4))

## TODO: Then perform Canny edge detection and display the output
blurred_gray = cv2.cvtColor(blurred_image, cv2.COLOR_RGB2GRAY)  
blurred_edges = cv2.Canny(blurred_gray,100,200)
# Dilate the image to amplify edges
blurred_edges = cv2.dilate(blurred_edges, None)

fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Blurred Image')
ax1.imshow(blurred_image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])
ax2.set_title('Canny Edges')
ax2.imshow(blurred_edges, cmap='gray')
Out[13]:
<matplotlib.image.AxesImage at 0x7fe728758320>

Step 4: Automatically Hide the Identity of an Individual

If you film something like a documentary or reality TV, you must get permission from every individual shown on film before you can show their face, otherwise you need to blur it out - by blurring the face a lot (so much so that even the global structures are obscured)! This is also true for projects like Google's StreetView maps - an enormous collection of mapping images taken from a fleet of Google vehicles. Because it would be impossible for Google to get the permission of every single person accidentally captured in one of these images they blur out everyone's faces, the detected images must automatically blur the identity of detected people. Here's a few examples of folks caught in the camera of a Google street view vehicle.

Read in an image to perform identity detection

Let's try this out for ourselves. Use the face detection pipeline built above and what you know about using the filter2D to blur and image, and use these in tandem to hide the identity of the person in the following image - loaded in and printed in the next cell.

In [14]:
# Load in the image
image = cv2.imread('images/gus.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Display the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[14]:
<matplotlib.image.AxesImage at 0x7fe7286e6390>

(IMPLEMENTATION) Use blurring to hide the identity of an individual in an image

The idea here is to 1) automatically detect the face in this image, and then 2) blur it out! Make sure to adjust the parameters of the averaging blur filter to completely obscure this person's identity.

In [17]:
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
classifier = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
faces = classifier.detectMultiScale(gray, 1.1, 10)

image_blurred = np.copy(image)
for (x,y,w,h) in faces:
    image_blurred[y:y+h,x:x+w] = cv2.blur(image_blurred[y:y+h,x:x+w], (100,100))

## TODO: Blur the bounding box around each detected face using an averaging filter and display the result
fig = plt.figure(figsize = (6, 6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Blurred Face')
ax1.imshow(image_blurred)
Out[17]:
<matplotlib.image.AxesImage at 0x7fe728501048>

(Optional) Build identity protection into your laptop camera

In this optional task you can add identity protection to your laptop camera, using the previously completed code where you added face detection to your laptop camera - and the task above. You should be able to get reasonable results with little parameter tuning - like the one shown in the gif below.

As with the previous video task, to make this perfect would require significant effort - so don't strive for perfection here, strive for reasonable quality.

The next cell contains code a wrapper function called laptop_camera_identity_hider that - when called - will activate your laptop's camera. You need to place the relevant face detection and blurring code developed above in this function in order to blur faces entering your laptop camera's field of view.

Before adding anything to the function you can call it to get a hang of how it works - a small window will pop up showing you the live feed from your camera, you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [55]:
### Insert face detection and blurring code into the wrapper below to create an identity protector on your laptop!
import cv2
import time 

def detectCascadeFeature(image, cascade):
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    features = cascade.detectMultiScale(gray, 1.08, 8)
    return features

def laptop_camera_go():
    # Initiate face cascade classifier
    face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        # Detect faces
        faces = detectCascadeFeature(frame,face_cascade)
        
        for (x,y,w,h) in faces:
            frame[y:y+h,x:x+w] = cv2.blur(frame[y:y+h,x:x+w], (50,50))
        
        # Plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
In [56]:
# Run laptop identity hider
laptop_camera_go()


Step 5: Create a CNN to Recognize Facial Keypoints

OpenCV is often used in practice with other machine learning and deep learning libraries to produce interesting results. In this stage of the project you will create your own end-to-end pipeline - employing convolutional networks in keras along with OpenCV - to apply a "selfie" filter to streaming video and images.

You will start by creating and then training a convolutional network that can detect facial keypoints in a small dataset of cropped images of human faces. We then guide you towards OpenCV to expanding your detection algorithm to more general images. What are facial keypoints? Let's take a look at some examples.

Facial keypoints (also called facial landmarks) are the small blue-green dots shown on each of the faces in the image above - there are 15 keypoints marked in each image. They mark important areas of the face - the eyes, corners of the mouth, the nose, etc. Facial keypoints can be used in a variety of machine learning applications from face and emotion recognition to commercial applications like the image filters popularized by Snapchat.

Below we illustrate a filter that, using the results of this section, automatically places sunglasses on people in images (using the facial keypoints to place the glasses correctly on each face). Here, the facial keypoints have been colored lime green for visualization purposes.

Make a facial keypoint detector

But first things first: how can we make a facial keypoint detector? Well, at a high level, notice that facial keypoint detection is a regression problem. A single face corresponds to a set of 15 facial keypoints (a set of 15 corresponding $(x, y)$ coordinates, i.e., an output point). Because our input data are images, we can employ a convolutional neural network to recognize patterns in our images and learn how to identify these keypoint given sets of labeled data.

In order to train a regressor, we need a training set - a set of facial image / facial keypoint pairs to train on. For this we will be using this dataset from Kaggle. We've already downloaded this data and placed it in the data directory. Make sure that you have both the training and test data files. The training dataset contains several thousand $96 \times 96$ grayscale images of cropped human faces, along with each face's 15 corresponding facial keypoints (also called landmarks) that have been placed by hand, and recorded in $(x, y)$ coordinates. This wonderful resource also has a substantial testing set, which we will use in tinkering with our convolutional network.

To load in this data, run the Python cell below - notice we will load in both the training and testing sets.

The load_data function is in the included utils.py file.

In [1]:
from utils import *

# Load training set
X_train, y_train = load_data()
print("X_train.shape == {}".format(X_train.shape))
print("y_train.shape == {}; y_train.min == {:.3f}; y_train.max == {:.3f}".format(
    y_train.shape, y_train.min(), y_train.max()))

# Load testing set
X_test, _ = load_data(test=True)
print("X_test.shape == {}".format(X_test.shape))
Using TensorFlow backend.
X_train.shape == (2140, 96, 96, 1)
y_train.shape == (2140, 30); y_train.min == -0.920; y_train.max == 0.996
X_test.shape == (1783, 96, 96, 1)

The load_data function in utils.py originates from this excellent blog post, which you are strongly encouraged to read. Please take the time now to review this function. Note how the output values - that is, the coordinates of each set of facial landmarks - have been normalized to take on values in the range $[-1, 1]$, while the pixel values of each input point (a facial image) have been normalized to the range $[0,1]$.

Note: the original Kaggle dataset contains some images with several missing keypoints. For simplicity, the load_data function removes those images with missing labels from the dataset. As an optional extension, you are welcome to amend the load_data function to include the incomplete data points.

Visualize the Training Data

Execute the code cell below to visualize a subset of the training data.

In [62]:
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_train[i], y_train[i], ax)

For each training image, there are two landmarks per eyebrow (four total), three per eye (six total), four for the mouth, and one for the tip of the nose.

Review the plot_data function in utils.py to understand how the 30-dimensional training labels in y_train are mapped to facial locations, as this function will prove useful for your pipeline.

(IMPLEMENTATION) Specify the CNN Architecture

In this section, you will specify a neural network for predicting the locations of facial keypoints. Use the code cell below to specify the architecture of your neural network. We have imported some layers that you may find useful for this task, but if you need to use more Keras layers, feel free to import them in the cell.

Your network should accept a $96 \times 96$ grayscale image as input, and it should output a vector with 30 entries, corresponding to the predicted (horizontal and vertical) locations of 15 facial keypoints. If you are not sure where to start, you can find some useful starting architectures in this blog, but you are not permitted to copy any of the architectures that you find online.

In [2]:
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, Dropout
from keras.layers import Flatten, Dense


## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)
def makeModel(n_conv_layers = 6, n_final_features = 1024, dropout = 0.5):
    # A linear convolutional neural network generator to create 2~6 layers of convolution layer with 2x2 convolution layers (except the first layer)
    # Created to make automatic architecture tests possible
    
    assert isinstance(n_conv_layers,int) & isinstance(n_final_features,int), 'n_conv_layers and n_final_features must be integer values'
    assert (n_conv_layers >= 2) & (n_conv_layers <= 6), 'n_conv_layers must be an integer value between 2 and 6'
    assert n_final_features % 2**(n_conv_layers - 1) == 0, 'n_final_features must be divisible by 2^(n_conv_layers-1)'
    assert (dropout >= 0) & (dropout < 1), 'dropout must be a float value between 0 and 1'
    
    n_init_filters = n_final_features // (2**(n_conv_layers-1))
    model = Sequential()
    model.add(Conv2D(filters=n_init_filters, kernel_size=3, padding='same', activation='relu', input_shape=(96,96,1)))
    model.add(MaxPooling2D(pool_size=3))
    for i in range(1,n_conv_layers-1):
        model.add(Conv2D(filters=(2**i)*n_init_filters, kernel_size=2, padding='same', activation='relu'))
        model.add(MaxPooling2D(pool_size=2))
    model.add(Conv2D(filters=(2**(n_conv_layers-1))*n_init_filters, kernel_size=2, padding='same', activation='relu'))
    model.add(GlobalAveragePooling2D())
    model.add(Dropout(0.5))
    model.add(Dense(30))
    return model

#model = makeModel(n_conv_layers = 6, n_final_features = 1024, dropout = 0.5)

# Summarize the model
#model.summary()

Step 6: Compile and Train the Model

After specifying your architecture, you'll need to compile and train the model to detect facial keypoints'

(IMPLEMENTATION) Compile and Train the Model

Use the compile method to configure the learning process. Experiment with your choice of optimizer; you may have some ideas about which will work best (SGD vs. RMSprop, etc), but take the time to empirically verify your theories.

Use the fit method to train the model. Break off a validation set by setting validation_split=0.2. Save the returned History object in the history variable.

Your model is required to attain a validation loss (measured as mean squared error) of at least XYZ. When you have finished training, save your model as an HDF5 file with file path my_model.h5.

In [ ]:
from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam

## TODO: Compile the model
model.compile(optimizer='rmsprop', loss='mean_squared_error')

## TODO: Train the model
hist = model.fit(X_train, y_train, batch_size=428, epochs=200, verbose=2, validation_split=0.2)

## TODO: Save the model as model.h5
#model.save('my_model.h5')
In [27]:
plt.figure(figsize=(20,8))
for i, optimizer in enumerate(['sgd', 'rmsprop', 'adagrad', 'adadelta', 'adam', 'adamax', 'nadam']):
    model = makeModel(n_conv_layers=3, n_final_features=256, dropout=0.2)
    model.compile(optimizer=optimizer, loss='mean_squared_error')
    hist = model.fit(X_train, y_train, batch_size=32, epochs=30, verbose=0, validation_split=0.2)
    plt.subplot(241+i)
    plt.plot(hist.epoch, hist.history['loss'],'r',hist.epoch, hist.history['val_loss'],'b')
    plt.title(optimizer);plt.xlabel('epoch');plt.ylabel('rms loss')
plt.show()

I tested all seven optimizers and plotted all the losses. I forgot to plot them on all same y-axes, but I think you can still see some clear winners. One of them is RMSProp, which I will use below.

Quick explanation of next few slides: I first do a grid search on few parameters---number of layers, number of filters, and dropout value. Then I choose two model---one that performs the best and another that performs well but with significantly less parameters (trading minor performance reduction for speed).

In [34]:
layers = [2, 3, 4, 5]
final_features = [128, 256, 512]
dropouts = [0.1, 0.3, 0.5]
hists = []
for layer in layers:
    for n_features in final_features:
        for dropout in dropouts:
            print('Optimizer = %s, Conv Layers = %d, # of Final Features = %d, Dropout = %f' %(optimizer, layer, n_features, dropout))
            # Make model with each layer, n_features, and dropout and train using RMSProp
            model = makeModel(n_conv_layers=layer, n_final_features=n_features, dropout=dropout)
            model.compile(optimizer='rmsprop', loss='mean_squared_error')
            hist = model.fit(X_train, y_train, batch_size=32, epochs=50, verbose=0, validation_split=0.2)
            #Look up the lowest validation loss in history (and the corresponding epoch and training loss)
            min_valloss = min(hist.history['val_loss'])
            min_epoch_loss = min(enumerate(hist.history['loss']), key=lambda tup:hist.history['val_loss'][tup[0]])
            #Save the values
            hists.append([layer,n_features,dropout,min_epoch_loss,min_valloss])
            print('    Min Val Loss: Epoch = %d , Loss = %f , Validation loss = %f' %(min_epoch_loss[0]+1, min_epoch_loss[1], min_valloss))
Optimizer = nadam, Conv Layers = 2, # of Final Features = 128, Dropout = 0.100000
    Min Val Loss: Epoch = 49 , Loss = 0.004171 , Validation loss = 0.004013
Optimizer = nadam, Conv Layers = 2, # of Final Features = 128, Dropout = 0.300000
    Min Val Loss: Epoch = 48 , Loss = 0.004192 , Validation loss = 0.004057
Optimizer = nadam, Conv Layers = 2, # of Final Features = 128, Dropout = 0.500000
    Min Val Loss: Epoch = 50 , Loss = 0.004152 , Validation loss = 0.004016
Optimizer = nadam, Conv Layers = 2, # of Final Features = 256, Dropout = 0.100000
    Min Val Loss: Epoch = 47 , Loss = 0.004153 , Validation loss = 0.003925
Optimizer = nadam, Conv Layers = 2, # of Final Features = 256, Dropout = 0.300000
    Min Val Loss: Epoch = 45 , Loss = 0.004198 , Validation loss = 0.004011
Optimizer = nadam, Conv Layers = 2, # of Final Features = 256, Dropout = 0.500000
    Min Val Loss: Epoch = 44 , Loss = 0.004190 , Validation loss = 0.003992
Optimizer = nadam, Conv Layers = 2, # of Final Features = 512, Dropout = 0.100000
    Min Val Loss: Epoch = 47 , Loss = 0.004162 , Validation loss = 0.003890
Optimizer = nadam, Conv Layers = 2, # of Final Features = 512, Dropout = 0.300000
    Min Val Loss: Epoch = 43 , Loss = 0.004169 , Validation loss = 0.003891
Optimizer = nadam, Conv Layers = 2, # of Final Features = 512, Dropout = 0.500000
    Min Val Loss: Epoch = 48 , Loss = 0.004174 , Validation loss = 0.003895
Optimizer = nadam, Conv Layers = 3, # of Final Features = 128, Dropout = 0.100000
    Min Val Loss: Epoch = 49 , Loss = 0.003794 , Validation loss = 0.003731
Optimizer = nadam, Conv Layers = 3, # of Final Features = 128, Dropout = 0.300000
    Min Val Loss: Epoch = 45 , Loss = 0.003761 , Validation loss = 0.003615
Optimizer = nadam, Conv Layers = 3, # of Final Features = 128, Dropout = 0.500000
    Min Val Loss: Epoch = 49 , Loss = 0.003793 , Validation loss = 0.003685
Optimizer = nadam, Conv Layers = 3, # of Final Features = 256, Dropout = 0.100000
    Min Val Loss: Epoch = 50 , Loss = 0.003582 , Validation loss = 0.003513
Optimizer = nadam, Conv Layers = 3, # of Final Features = 256, Dropout = 0.300000
    Min Val Loss: Epoch = 43 , Loss = 0.003723 , Validation loss = 0.003508
Optimizer = nadam, Conv Layers = 3, # of Final Features = 256, Dropout = 0.500000
    Min Val Loss: Epoch = 50 , Loss = 0.003551 , Validation loss = 0.003459
Optimizer = nadam, Conv Layers = 3, # of Final Features = 512, Dropout = 0.100000
    Min Val Loss: Epoch = 50 , Loss = 0.003442 , Validation loss = 0.003177
Optimizer = nadam, Conv Layers = 3, # of Final Features = 512, Dropout = 0.300000
    Min Val Loss: Epoch = 47 , Loss = 0.003445 , Validation loss = 0.003392
Optimizer = nadam, Conv Layers = 3, # of Final Features = 512, Dropout = 0.500000
    Min Val Loss: Epoch = 49 , Loss = 0.003363 , Validation loss = 0.003296
Optimizer = nadam, Conv Layers = 4, # of Final Features = 128, Dropout = 0.100000
    Min Val Loss: Epoch = 50 , Loss = 0.003266 , Validation loss = 0.003186
Optimizer = nadam, Conv Layers = 4, # of Final Features = 128, Dropout = 0.300000
    Min Val Loss: Epoch = 50 , Loss = 0.003461 , Validation loss = 0.003445
Optimizer = nadam, Conv Layers = 4, # of Final Features = 128, Dropout = 0.500000
    Min Val Loss: Epoch = 49 , Loss = 0.003460 , Validation loss = 0.003425
Optimizer = nadam, Conv Layers = 4, # of Final Features = 256, Dropout = 0.100000
    Min Val Loss: Epoch = 49 , Loss = 0.002989 , Validation loss = 0.003031
Optimizer = nadam, Conv Layers = 4, # of Final Features = 256, Dropout = 0.300000
    Min Val Loss: Epoch = 49 , Loss = 0.003012 , Validation loss = 0.003129
Optimizer = nadam, Conv Layers = 4, # of Final Features = 256, Dropout = 0.500000
    Min Val Loss: Epoch = 49 , Loss = 0.003096 , Validation loss = 0.003145
Optimizer = nadam, Conv Layers = 4, # of Final Features = 512, Dropout = 0.100000
    Min Val Loss: Epoch = 47 , Loss = 0.002808 , Validation loss = 0.002779
Optimizer = nadam, Conv Layers = 4, # of Final Features = 512, Dropout = 0.300000
    Min Val Loss: Epoch = 47 , Loss = 0.002834 , Validation loss = 0.002870
Optimizer = nadam, Conv Layers = 4, # of Final Features = 512, Dropout = 0.500000
    Min Val Loss: Epoch = 50 , Loss = 0.002694 , Validation loss = 0.002947
Optimizer = nadam, Conv Layers = 5, # of Final Features = 128, Dropout = 0.100000
    Min Val Loss: Epoch = 50 , Loss = 0.002469 , Validation loss = 0.002342
Optimizer = nadam, Conv Layers = 5, # of Final Features = 128, Dropout = 0.300000
    Min Val Loss: Epoch = 49 , Loss = 0.002547 , Validation loss = 0.002476
Optimizer = nadam, Conv Layers = 5, # of Final Features = 128, Dropout = 0.500000
    Min Val Loss: Epoch = 50 , Loss = 0.002570 , Validation loss = 0.002581
Optimizer = nadam, Conv Layers = 5, # of Final Features = 256, Dropout = 0.100000
    Min Val Loss: Epoch = 47 , Loss = 0.001969 , Validation loss = 0.001877
Optimizer = nadam, Conv Layers = 5, # of Final Features = 256, Dropout = 0.300000
    Min Val Loss: Epoch = 49 , Loss = 0.001910 , Validation loss = 0.002014
Optimizer = nadam, Conv Layers = 5, # of Final Features = 256, Dropout = 0.500000
    Min Val Loss: Epoch = 47 , Loss = 0.002099 , Validation loss = 0.001853
Optimizer = nadam, Conv Layers = 5, # of Final Features = 512, Dropout = 0.100000
    Min Val Loss: Epoch = 49 , Loss = 0.001501 , Validation loss = 0.001625
Optimizer = nadam, Conv Layers = 5, # of Final Features = 512, Dropout = 0.300000
    Min Val Loss: Epoch = 50 , Loss = 0.001581 , Validation loss = 0.001773
Optimizer = nadam, Conv Layers = 5, # of Final Features = 512, Dropout = 0.500000
    Min Val Loss: Epoch = 50 , Loss = 0.001602 , Validation loss = 0.001721
In [44]:
sorted(hists,key=lambda x:x[4])
Out[44]:
[[5, 512, 0.1, (48, 0.0015006840803495078), 0.0016252668008695697],
 [5, 512, 0.5, (49, 0.0016024416969723512), 0.0017207254379308808],
 [5, 512, 0.3, (49, 0.001580618265319929), 0.0017734267857691674],
 [5, 256, 0.5, (46, 0.0020991068640201587), 0.0018532872200012207],
 [5, 256, 0.1, (46, 0.0019689172867546293), 0.0018770802726916899],
 [5, 256, 0.3, (48, 0.0019104770704599045), 0.0020144521846287996],
 [5, 128, 0.1, (49, 0.0024691551888936032), 0.0023416511335836673],
 [5, 128, 0.3, (48, 0.0025466519579830987), 0.0024764883140467593],
 [5, 128, 0.5, (49, 0.002570459941210591), 0.0025812877455256254],
 [4, 512, 0.1, (46, 0.002807839122975123), 0.0027794610909142783],
 [4, 512, 0.3, (46, 0.0028337162710447734), 0.002869895413500544],
 [4, 512, 0.5, (49, 0.0026940520075976709), 0.0029465440382188727],
 [4, 256, 0.1, (48, 0.0029892245107373903), 0.0030307534072443704],
 [4, 256, 0.3, (48, 0.003011618131580197), 0.003129240647654667],
 [4, 256, 0.5, (48, 0.0030964450131683984), 0.0031446230066853151],
 [3, 512, 0.1, (49, 0.0034423439619871224), 0.0031771574378292138],
 [4, 128, 0.1, (49, 0.0032663398692123246), 0.0031860550935162561],
 [3, 512, 0.5, (48, 0.0033631737444062377), 0.0032961891145906717],
 [3, 512, 0.3, (46, 0.0034453476666011541), 0.0033915663164143807],
 [4, 128, 0.5, (48, 0.0034600656009583829), 0.0034252121026201224],
 [4, 128, 0.3, (49, 0.003460635000265369), 0.0034446210913777909],
 [3, 256, 0.5, (49, 0.00355061733546867), 0.0034594865098038566],
 [3, 256, 0.3, (42, 0.0037225502473519786), 0.0035076528683165523],
 [3, 256, 0.1, (49, 0.0035816664703051063), 0.0035132504346841406],
 [3, 128, 0.3, (44, 0.0037611322064022316), 0.0036148413075743433],
 [3, 128, 0.5, (48, 0.0037929392463275204), 0.0036846421850479654],
 [3, 128, 0.1, (48, 0.003793765629737455), 0.0037305858639007975],
 [2, 512, 0.1, (46, 0.0041621645616593764), 0.0038901953131099728],
 [2, 512, 0.3, (42, 0.0041694707415615012), 0.0038910117740177104],
 [2, 512, 0.5, (47, 0.0041738468348527348), 0.0038952045882486293],
 [2, 256, 0.1, (46, 0.0041529576372459666), 0.0039249268995824264],
 [2, 256, 0.5, (43, 0.004189611282025542), 0.0039916052787660437],
 [2, 256, 0.3, (44, 0.004198149952027842), 0.0040106953852853486],
 [2, 128, 0.1, (48, 0.0041709667654864701), 0.0040133807842976576],
 [2, 128, 0.5, (49, 0.0041518508082377574), 0.0040161518301710351],
 [2, 128, 0.3, (47, 0.0041922483414794515), 0.0040573446410838692]]
In [45]:
## Make the model
model = makeModel(n_conv_layers=5, n_final_features=512, dropout=0.1)
## Compile the model
model.compile(optimizer='rmsprop', loss='mean_squared_error')
## Train the model
hist = model.fit(X_train, y_train, batch_size=107, epochs=200, verbose=2, validation_split=0.2)
## TODO: Save the model as model.h5
model.save('my_model.h5')
Train on 1712 samples, validate on 428 samples
Epoch 1/200
3s - loss: 0.0951 - val_loss: 0.0096
Epoch 2/200
1s - loss: 0.0177 - val_loss: 0.0106
Epoch 3/200
1s - loss: 0.0192 - val_loss: 0.0094
Epoch 4/200
1s - loss: 0.0182 - val_loss: 0.0054
Epoch 5/200
1s - loss: 0.0145 - val_loss: 0.0081
Epoch 6/200
1s - loss: 0.0119 - val_loss: 0.0072
Epoch 7/200
1s - loss: 0.0107 - val_loss: 0.0048
Epoch 8/200
1s - loss: 0.0091 - val_loss: 0.0054
Epoch 9/200
1s - loss: 0.0080 - val_loss: 0.0053
Epoch 10/200
1s - loss: 0.0077 - val_loss: 0.0049
Epoch 11/200
1s - loss: 0.0070 - val_loss: 0.0058
Epoch 12/200
1s - loss: 0.0073 - val_loss: 0.0050
Epoch 13/200
1s - loss: 0.0065 - val_loss: 0.0044
Epoch 14/200
1s - loss: 0.0064 - val_loss: 0.0045
Epoch 15/200
1s - loss: 0.0062 - val_loss: 0.0044
Epoch 16/200
1s - loss: 0.0060 - val_loss: 0.0047
Epoch 17/200
1s - loss: 0.0059 - val_loss: 0.0051
Epoch 18/200
1s - loss: 0.0059 - val_loss: 0.0043
Epoch 19/200
1s - loss: 0.0055 - val_loss: 0.0044
Epoch 20/200
1s - loss: 0.0054 - val_loss: 0.0045
Epoch 21/200
1s - loss: 0.0054 - val_loss: 0.0043
Epoch 22/200
1s - loss: 0.0054 - val_loss: 0.0045
Epoch 23/200
1s - loss: 0.0052 - val_loss: 0.0044
Epoch 24/200
1s - loss: 0.0051 - val_loss: 0.0048
Epoch 25/200
1s - loss: 0.0052 - val_loss: 0.0044
Epoch 26/200
1s - loss: 0.0051 - val_loss: 0.0048
Epoch 27/200
1s - loss: 0.0050 - val_loss: 0.0042
Epoch 28/200
1s - loss: 0.0050 - val_loss: 0.0042
Epoch 29/200
1s - loss: 0.0050 - val_loss: 0.0047
Epoch 30/200
1s - loss: 0.0048 - val_loss: 0.0045
Epoch 31/200
1s - loss: 0.0049 - val_loss: 0.0043
Epoch 32/200
1s - loss: 0.0049 - val_loss: 0.0041
Epoch 33/200
1s - loss: 0.0046 - val_loss: 0.0041
Epoch 34/200
1s - loss: 0.0048 - val_loss: 0.0040
Epoch 35/200
1s - loss: 0.0045 - val_loss: 0.0047
Epoch 36/200
1s - loss: 0.0046 - val_loss: 0.0040
Epoch 37/200
1s - loss: 0.0045 - val_loss: 0.0043
Epoch 38/200
1s - loss: 0.0045 - val_loss: 0.0040
Epoch 39/200
1s - loss: 0.0044 - val_loss: 0.0039
Epoch 40/200
1s - loss: 0.0043 - val_loss: 0.0041
Epoch 41/200
1s - loss: 0.0043 - val_loss: 0.0040
Epoch 42/200
1s - loss: 0.0041 - val_loss: 0.0052
Epoch 43/200
1s - loss: 0.0042 - val_loss: 0.0038
Epoch 44/200
1s - loss: 0.0040 - val_loss: 0.0036
Epoch 45/200
1s - loss: 0.0041 - val_loss: 0.0035
Epoch 46/200
1s - loss: 0.0039 - val_loss: 0.0043
Epoch 47/200
1s - loss: 0.0039 - val_loss: 0.0042
Epoch 48/200
1s - loss: 0.0040 - val_loss: 0.0036
Epoch 49/200
1s - loss: 0.0038 - val_loss: 0.0035
Epoch 50/200
1s - loss: 0.0037 - val_loss: 0.0033
Epoch 51/200
1s - loss: 0.0038 - val_loss: 0.0034
Epoch 52/200
1s - loss: 0.0037 - val_loss: 0.0039
Epoch 53/200
1s - loss: 0.0036 - val_loss: 0.0031
Epoch 54/200
1s - loss: 0.0034 - val_loss: 0.0034
Epoch 55/200
1s - loss: 0.0033 - val_loss: 0.0036
Epoch 56/200
1s - loss: 0.0035 - val_loss: 0.0035
Epoch 57/200
1s - loss: 0.0033 - val_loss: 0.0031
Epoch 58/200
1s - loss: 0.0033 - val_loss: 0.0034
Epoch 59/200
1s - loss: 0.0032 - val_loss: 0.0043
Epoch 60/200
1s - loss: 0.0032 - val_loss: 0.0045
Epoch 61/200
1s - loss: 0.0032 - val_loss: 0.0028
Epoch 62/200
1s - loss: 0.0030 - val_loss: 0.0028
Epoch 63/200
1s - loss: 0.0029 - val_loss: 0.0028
Epoch 64/200
1s - loss: 0.0030 - val_loss: 0.0030
Epoch 65/200
1s - loss: 0.0028 - val_loss: 0.0026
Epoch 66/200
1s - loss: 0.0029 - val_loss: 0.0026
Epoch 67/200
1s - loss: 0.0027 - val_loss: 0.0033
Epoch 68/200
1s - loss: 0.0028 - val_loss: 0.0031
Epoch 69/200
1s - loss: 0.0027 - val_loss: 0.0025
Epoch 70/200
1s - loss: 0.0027 - val_loss: 0.0029
Epoch 71/200
1s - loss: 0.0027 - val_loss: 0.0027
Epoch 72/200
1s - loss: 0.0026 - val_loss: 0.0023
Epoch 73/200
1s - loss: 0.0025 - val_loss: 0.0025
Epoch 74/200
1s - loss: 0.0026 - val_loss: 0.0024
Epoch 75/200
1s - loss: 0.0024 - val_loss: 0.0027
Epoch 76/200
1s - loss: 0.0025 - val_loss: 0.0030
Epoch 77/200
1s - loss: 0.0025 - val_loss: 0.0025
Epoch 78/200
1s - loss: 0.0024 - val_loss: 0.0027
Epoch 79/200
1s - loss: 0.0023 - val_loss: 0.0027
Epoch 80/200
1s - loss: 0.0024 - val_loss: 0.0024
Epoch 81/200
1s - loss: 0.0023 - val_loss: 0.0027
Epoch 82/200
1s - loss: 0.0023 - val_loss: 0.0024
Epoch 83/200
1s - loss: 0.0022 - val_loss: 0.0023
Epoch 84/200
1s - loss: 0.0023 - val_loss: 0.0029
Epoch 85/200
1s - loss: 0.0021 - val_loss: 0.0035
Epoch 86/200
1s - loss: 0.0022 - val_loss: 0.0025
Epoch 87/200
1s - loss: 0.0020 - val_loss: 0.0024
Epoch 88/200
1s - loss: 0.0021 - val_loss: 0.0029
Epoch 89/200
1s - loss: 0.0020 - val_loss: 0.0028
Epoch 90/200
1s - loss: 0.0020 - val_loss: 0.0032
Epoch 91/200
1s - loss: 0.0019 - val_loss: 0.0022
Epoch 92/200
1s - loss: 0.0021 - val_loss: 0.0021
Epoch 93/200
1s - loss: 0.0019 - val_loss: 0.0022
Epoch 94/200
1s - loss: 0.0019 - val_loss: 0.0023
Epoch 95/200
1s - loss: 0.0019 - val_loss: 0.0020
Epoch 96/200
1s - loss: 0.0018 - val_loss: 0.0021
Epoch 97/200
1s - loss: 0.0019 - val_loss: 0.0020
Epoch 98/200
1s - loss: 0.0018 - val_loss: 0.0022
Epoch 99/200
1s - loss: 0.0018 - val_loss: 0.0019
Epoch 100/200
1s - loss: 0.0019 - val_loss: 0.0022
Epoch 101/200
1s - loss: 0.0017 - val_loss: 0.0024
Epoch 102/200
1s - loss: 0.0017 - val_loss: 0.0022
Epoch 103/200
1s - loss: 0.0018 - val_loss: 0.0021
Epoch 104/200
1s - loss: 0.0016 - val_loss: 0.0028
Epoch 105/200
1s - loss: 0.0017 - val_loss: 0.0039
Epoch 106/200
1s - loss: 0.0018 - val_loss: 0.0021
Epoch 107/200
1s - loss: 0.0017 - val_loss: 0.0019
Epoch 108/200
1s - loss: 0.0016 - val_loss: 0.0019
Epoch 109/200
1s - loss: 0.0017 - val_loss: 0.0022
Epoch 110/200
1s - loss: 0.0016 - val_loss: 0.0031
Epoch 111/200
1s - loss: 0.0015 - val_loss: 0.0018
Epoch 112/200
1s - loss: 0.0016 - val_loss: 0.0019
Epoch 113/200
1s - loss: 0.0015 - val_loss: 0.0020
Epoch 114/200
1s - loss: 0.0015 - val_loss: 0.0018
Epoch 115/200
1s - loss: 0.0016 - val_loss: 0.0019
Epoch 116/200
1s - loss: 0.0015 - val_loss: 0.0019
Epoch 117/200
1s - loss: 0.0015 - val_loss: 0.0019
Epoch 118/200
1s - loss: 0.0015 - val_loss: 0.0022
Epoch 119/200
1s - loss: 0.0014 - val_loss: 0.0019
Epoch 120/200
1s - loss: 0.0015 - val_loss: 0.0017
Epoch 121/200
1s - loss: 0.0014 - val_loss: 0.0022
Epoch 122/200
1s - loss: 0.0015 - val_loss: 0.0019
Epoch 123/200
1s - loss: 0.0015 - val_loss: 0.0017
Epoch 124/200
1s - loss: 0.0014 - val_loss: 0.0021
Epoch 125/200
1s - loss: 0.0013 - val_loss: 0.0019
Epoch 126/200
1s - loss: 0.0015 - val_loss: 0.0022
Epoch 127/200
1s - loss: 0.0013 - val_loss: 0.0027
Epoch 128/200
1s - loss: 0.0014 - val_loss: 0.0021
Epoch 129/200
1s - loss: 0.0013 - val_loss: 0.0018
Epoch 130/200
1s - loss: 0.0014 - val_loss: 0.0019
Epoch 131/200
1s - loss: 0.0014 - val_loss: 0.0021
Epoch 132/200
1s - loss: 0.0012 - val_loss: 0.0024
Epoch 133/200
1s - loss: 0.0013 - val_loss: 0.0019
Epoch 134/200
1s - loss: 0.0013 - val_loss: 0.0018
Epoch 135/200
1s - loss: 0.0014 - val_loss: 0.0018
Epoch 136/200
1s - loss: 0.0012 - val_loss: 0.0018
Epoch 137/200
1s - loss: 0.0013 - val_loss: 0.0018
Epoch 138/200
1s - loss: 0.0014 - val_loss: 0.0020
Epoch 139/200
1s - loss: 0.0012 - val_loss: 0.0018
Epoch 140/200
1s - loss: 0.0013 - val_loss: 0.0022
Epoch 141/200
1s - loss: 0.0012 - val_loss: 0.0021
Epoch 142/200
1s - loss: 0.0011 - val_loss: 0.0018
Epoch 143/200
1s - loss: 0.0012 - val_loss: 0.0018
Epoch 144/200
1s - loss: 0.0012 - val_loss: 0.0020
Epoch 145/200
1s - loss: 0.0012 - val_loss: 0.0018
Epoch 146/200
1s - loss: 0.0012 - val_loss: 0.0017
Epoch 147/200
1s - loss: 0.0012 - val_loss: 0.0018
Epoch 148/200
1s - loss: 0.0012 - val_loss: 0.0018
Epoch 149/200
1s - loss: 0.0012 - val_loss: 0.0018
Epoch 150/200
1s - loss: 0.0011 - val_loss: 0.0025
Epoch 151/200
1s - loss: 0.0012 - val_loss: 0.0023
Epoch 152/200
1s - loss: 0.0012 - val_loss: 0.0022
Epoch 153/200
1s - loss: 0.0010 - val_loss: 0.0021
Epoch 154/200
1s - loss: 0.0011 - val_loss: 0.0022
Epoch 155/200
1s - loss: 0.0011 - val_loss: 0.0017
Epoch 156/200
1s - loss: 0.0012 - val_loss: 0.0019
Epoch 157/200
1s - loss: 0.0011 - val_loss: 0.0024
Epoch 158/200
1s - loss: 0.0011 - val_loss: 0.0016
Epoch 159/200
1s - loss: 0.0011 - val_loss: 0.0022
Epoch 160/200
1s - loss: 0.0010 - val_loss: 0.0020
Epoch 161/200
1s - loss: 0.0011 - val_loss: 0.0018
Epoch 162/200
1s - loss: 0.0011 - val_loss: 0.0019
Epoch 163/200
1s - loss: 0.0010 - val_loss: 0.0028
Epoch 164/200
1s - loss: 0.0010 - val_loss: 0.0016
Epoch 165/200
1s - loss: 0.0011 - val_loss: 0.0016
Epoch 166/200
1s - loss: 0.0010 - val_loss: 0.0017
Epoch 167/200
1s - loss: 0.0010 - val_loss: 0.0017
Epoch 168/200
1s - loss: 0.0010 - val_loss: 0.0016
Epoch 169/200
1s - loss: 0.0011 - val_loss: 0.0016
Epoch 170/200
1s - loss: 0.0010 - val_loss: 0.0016
Epoch 171/200
1s - loss: 0.0010 - val_loss: 0.0020
Epoch 172/200
1s - loss: 0.0010 - val_loss: 0.0017
Epoch 173/200
1s - loss: 9.5742e-04 - val_loss: 0.0017
Epoch 174/200
1s - loss: 0.0010 - val_loss: 0.0021
Epoch 175/200
1s - loss: 9.7625e-04 - val_loss: 0.0018
Epoch 176/200
1s - loss: 9.7308e-04 - val_loss: 0.0019
Epoch 177/200
1s - loss: 9.9950e-04 - val_loss: 0.0017
Epoch 178/200
1s - loss: 9.2779e-04 - val_loss: 0.0017
Epoch 179/200
1s - loss: 9.8574e-04 - val_loss: 0.0018
Epoch 180/200
1s - loss: 9.3384e-04 - val_loss: 0.0020
Epoch 181/200
1s - loss: 9.2588e-04 - val_loss: 0.0018
Epoch 182/200
1s - loss: 9.8168e-04 - val_loss: 0.0016
Epoch 183/200
1s - loss: 9.6175e-04 - val_loss: 0.0018
Epoch 184/200
1s - loss: 8.9546e-04 - val_loss: 0.0016
Epoch 185/200
1s - loss: 9.6173e-04 - val_loss: 0.0016
Epoch 186/200
1s - loss: 8.8159e-04 - val_loss: 0.0016
Epoch 187/200
1s - loss: 9.5748e-04 - val_loss: 0.0015
Epoch 188/200
1s - loss: 9.3559e-04 - val_loss: 0.0017
Epoch 189/200
1s - loss: 8.4075e-04 - val_loss: 0.0019
Epoch 190/200
1s - loss: 9.1539e-04 - val_loss: 0.0016
Epoch 191/200
1s - loss: 8.7815e-04 - val_loss: 0.0021
Epoch 192/200
1s - loss: 9.1914e-04 - val_loss: 0.0016
Epoch 193/200
1s - loss: 9.0850e-04 - val_loss: 0.0017
Epoch 194/200
1s - loss: 8.9762e-04 - val_loss: 0.0015
Epoch 195/200
1s - loss: 9.0513e-04 - val_loss: 0.0016
Epoch 196/200
1s - loss: 8.5971e-04 - val_loss: 0.0018
Epoch 197/200
1s - loss: 8.6993e-04 - val_loss: 0.0017
Epoch 198/200
1s - loss: 8.7818e-04 - val_loss: 0.0020
Epoch 199/200
1s - loss: 8.4358e-04 - val_loss: 0.0018
Epoch 200/200
1s - loss: 9.1283e-04 - val_loss: 0.0015
In [46]:
## TODO: Visualize the training and validation loss of your neural network
_, (ax1, ax2) = plt.subplots(1,2,figsize=(24,8))

ax1.plot(hist.epoch, hist.history['loss'],'r')
ax1.plot(hist.epoch, hist.history['val_loss'],'b')
ax1.set_title('Full 200 epochs')
ax1.legend(['Training loss','Validation loss'])
ax1.set_xlabel('Epoch');ax1.set_ylabel('RMS Loss')

k_epoch = 50
ax2.plot(hist.epoch[:k_epoch+1], hist.history['loss'][:k_epoch+1],'r')
ax2.plot(hist.epoch[:k_epoch+1], hist.history['val_loss'][:k_epoch+1],'b')
ax2.set_title('First %d epochs' %k_epoch)
ax2.legend(['Training loss','Validation loss'])
ax2.set_xlabel('Epoch');ax2.set_ylabel('RMS Loss')
plt.show()
In [56]:
## Make the model
model = makeModel(n_conv_layers=5, n_final_features=128, dropout=0.1)
## Compile the model
model.compile(optimizer='rmsprop', loss='mean_squared_error')
## Train the model
hist = model.fit(X_train, y_train, batch_size=107, epochs=200, verbose=2, validation_split=0.2)
## TODO: Save the model as model.h5
model.save('my_model_fast.h5')
Train on 1712 samples, validate on 428 samples
Epoch 1/200
2s - loss: 0.0511 - val_loss: 0.0120
Epoch 2/200
0s - loss: 0.0237 - val_loss: 0.0148
Epoch 3/200
0s - loss: 0.0187 - val_loss: 0.0065
Epoch 4/200
0s - loss: 0.0160 - val_loss: 0.0107
Epoch 5/200
0s - loss: 0.0136 - val_loss: 0.0059
Epoch 6/200
0s - loss: 0.0120 - val_loss: 0.0078
Epoch 7/200
0s - loss: 0.0109 - val_loss: 0.0088
Epoch 8/200
0s - loss: 0.0097 - val_loss: 0.0128
Epoch 9/200
0s - loss: 0.0090 - val_loss: 0.0045
Epoch 10/200
0s - loss: 0.0089 - val_loss: 0.0084
Epoch 11/200
0s - loss: 0.0084 - val_loss: 0.0057
Epoch 12/200
0s - loss: 0.0078 - val_loss: 0.0045
Epoch 13/200
0s - loss: 0.0074 - val_loss: 0.0044
Epoch 14/200
0s - loss: 0.0073 - val_loss: 0.0052
Epoch 15/200
0s - loss: 0.0071 - val_loss: 0.0044
Epoch 16/200
0s - loss: 0.0067 - val_loss: 0.0044
Epoch 17/200
0s - loss: 0.0067 - val_loss: 0.0053
Epoch 18/200
0s - loss: 0.0064 - val_loss: 0.0047
Epoch 19/200
0s - loss: 0.0064 - val_loss: 0.0043
Epoch 20/200
0s - loss: 0.0062 - val_loss: 0.0043
Epoch 21/200
0s - loss: 0.0059 - val_loss: 0.0055
Epoch 22/200
0s - loss: 0.0060 - val_loss: 0.0046
Epoch 23/200
0s - loss: 0.0059 - val_loss: 0.0044
Epoch 24/200
0s - loss: 0.0059 - val_loss: 0.0043
Epoch 25/200
0s - loss: 0.0056 - val_loss: 0.0047
Epoch 26/200
0s - loss: 0.0056 - val_loss: 0.0043
Epoch 27/200
0s - loss: 0.0056 - val_loss: 0.0050
Epoch 28/200
0s - loss: 0.0056 - val_loss: 0.0048
Epoch 29/200
0s - loss: 0.0054 - val_loss: 0.0044
Epoch 30/200
0s - loss: 0.0054 - val_loss: 0.0045
Epoch 31/200
0s - loss: 0.0054 - val_loss: 0.0043
Epoch 32/200
0s - loss: 0.0053 - val_loss: 0.0044
Epoch 33/200
0s - loss: 0.0052 - val_loss: 0.0045
Epoch 34/200
0s - loss: 0.0052 - val_loss: 0.0043
Epoch 35/200
0s - loss: 0.0051 - val_loss: 0.0042
Epoch 36/200
0s - loss: 0.0050 - val_loss: 0.0046
Epoch 37/200
0s - loss: 0.0051 - val_loss: 0.0044
Epoch 38/200
0s - loss: 0.0049 - val_loss: 0.0044
Epoch 39/200
0s - loss: 0.0050 - val_loss: 0.0045
Epoch 40/200
0s - loss: 0.0050 - val_loss: 0.0041
Epoch 41/200
0s - loss: 0.0049 - val_loss: 0.0041
Epoch 42/200
0s - loss: 0.0048 - val_loss: 0.0041
Epoch 43/200
0s - loss: 0.0048 - val_loss: 0.0042
Epoch 44/200
0s - loss: 0.0048 - val_loss: 0.0042
Epoch 45/200
0s - loss: 0.0048 - val_loss: 0.0041
Epoch 46/200
0s - loss: 0.0046 - val_loss: 0.0041
Epoch 47/200
0s - loss: 0.0047 - val_loss: 0.0040
Epoch 48/200
0s - loss: 0.0046 - val_loss: 0.0040
Epoch 49/200
0s - loss: 0.0046 - val_loss: 0.0041
Epoch 50/200
0s - loss: 0.0046 - val_loss: 0.0041
Epoch 51/200
0s - loss: 0.0044 - val_loss: 0.0042
Epoch 52/200
0s - loss: 0.0045 - val_loss: 0.0041
Epoch 53/200
0s - loss: 0.0045 - val_loss: 0.0039
Epoch 54/200
0s - loss: 0.0044 - val_loss: 0.0039
Epoch 55/200
0s - loss: 0.0044 - val_loss: 0.0042
Epoch 56/200
0s - loss: 0.0044 - val_loss: 0.0039
Epoch 57/200
0s - loss: 0.0043 - val_loss: 0.0037
Epoch 58/200
0s - loss: 0.0043 - val_loss: 0.0040
Epoch 59/200
0s - loss: 0.0042 - val_loss: 0.0038
Epoch 60/200
0s - loss: 0.0042 - val_loss: 0.0039
Epoch 61/200
0s - loss: 0.0041 - val_loss: 0.0038
Epoch 62/200
0s - loss: 0.0040 - val_loss: 0.0046
Epoch 63/200
0s - loss: 0.0042 - val_loss: 0.0039
Epoch 64/200
0s - loss: 0.0040 - val_loss: 0.0036
Epoch 65/200
0s - loss: 0.0041 - val_loss: 0.0036
Epoch 66/200
0s - loss: 0.0039 - val_loss: 0.0035
Epoch 67/200
0s - loss: 0.0040 - val_loss: 0.0040
Epoch 68/200
0s - loss: 0.0039 - val_loss: 0.0035
Epoch 69/200
0s - loss: 0.0038 - val_loss: 0.0037
Epoch 70/200
0s - loss: 0.0038 - val_loss: 0.0036
Epoch 71/200
0s - loss: 0.0038 - val_loss: 0.0036
Epoch 72/200
0s - loss: 0.0038 - val_loss: 0.0035
Epoch 73/200
0s - loss: 0.0037 - val_loss: 0.0033
Epoch 74/200
0s - loss: 0.0036 - val_loss: 0.0034
Epoch 75/200
0s - loss: 0.0037 - val_loss: 0.0033
Epoch 76/200
0s - loss: 0.0036 - val_loss: 0.0039
Epoch 77/200
0s - loss: 0.0037 - val_loss: 0.0033
Epoch 78/200
0s - loss: 0.0036 - val_loss: 0.0034
Epoch 79/200
0s - loss: 0.0036 - val_loss: 0.0034
Epoch 80/200
0s - loss: 0.0036 - val_loss: 0.0032
Epoch 81/200
0s - loss: 0.0035 - val_loss: 0.0033
Epoch 82/200
0s - loss: 0.0035 - val_loss: 0.0032
Epoch 83/200
0s - loss: 0.0034 - val_loss: 0.0037
Epoch 84/200
0s - loss: 0.0034 - val_loss: 0.0032
Epoch 85/200
0s - loss: 0.0034 - val_loss: 0.0035
Epoch 86/200
0s - loss: 0.0035 - val_loss: 0.0036
Epoch 87/200
0s - loss: 0.0033 - val_loss: 0.0033
Epoch 88/200
0s - loss: 0.0034 - val_loss: 0.0030
Epoch 89/200
0s - loss: 0.0034 - val_loss: 0.0032
Epoch 90/200
0s - loss: 0.0033 - val_loss: 0.0031
Epoch 91/200
0s - loss: 0.0032 - val_loss: 0.0032
Epoch 92/200
0s - loss: 0.0032 - val_loss: 0.0030
Epoch 93/200
0s - loss: 0.0032 - val_loss: 0.0030
Epoch 94/200
0s - loss: 0.0032 - val_loss: 0.0029
Epoch 95/200
0s - loss: 0.0032 - val_loss: 0.0030
Epoch 96/200
0s - loss: 0.0032 - val_loss: 0.0029
Epoch 97/200
0s - loss: 0.0031 - val_loss: 0.0029
Epoch 98/200
0s - loss: 0.0031 - val_loss: 0.0029
Epoch 99/200
0s - loss: 0.0031 - val_loss: 0.0028
Epoch 100/200
0s - loss: 0.0030 - val_loss: 0.0028
Epoch 101/200
0s - loss: 0.0031 - val_loss: 0.0030
Epoch 102/200
0s - loss: 0.0030 - val_loss: 0.0030
Epoch 103/200
0s - loss: 0.0030 - val_loss: 0.0027
Epoch 104/200
0s - loss: 0.0029 - val_loss: 0.0031
Epoch 105/200
0s - loss: 0.0029 - val_loss: 0.0029
Epoch 106/200
0s - loss: 0.0029 - val_loss: 0.0032
Epoch 107/200
0s - loss: 0.0030 - val_loss: 0.0027
Epoch 108/200
0s - loss: 0.0029 - val_loss: 0.0026
Epoch 109/200
0s - loss: 0.0029 - val_loss: 0.0026
Epoch 110/200
0s - loss: 0.0029 - val_loss: 0.0026
Epoch 111/200
0s - loss: 0.0028 - val_loss: 0.0026
Epoch 112/200
0s - loss: 0.0028 - val_loss: 0.0028
Epoch 113/200
0s - loss: 0.0028 - val_loss: 0.0027
Epoch 114/200
0s - loss: 0.0027 - val_loss: 0.0027
Epoch 115/200
0s - loss: 0.0028 - val_loss: 0.0028
Epoch 116/200
0s - loss: 0.0027 - val_loss: 0.0028
Epoch 117/200
0s - loss: 0.0027 - val_loss: 0.0027
Epoch 118/200
0s - loss: 0.0027 - val_loss: 0.0025
Epoch 119/200
0s - loss: 0.0027 - val_loss: 0.0025
Epoch 120/200
0s - loss: 0.0027 - val_loss: 0.0025
Epoch 121/200
0s - loss: 0.0026 - val_loss: 0.0025
Epoch 122/200
0s - loss: 0.0026 - val_loss: 0.0025
Epoch 123/200
0s - loss: 0.0026 - val_loss: 0.0028
Epoch 124/200
0s - loss: 0.0026 - val_loss: 0.0027
Epoch 125/200
0s - loss: 0.0027 - val_loss: 0.0025
Epoch 126/200
0s - loss: 0.0025 - val_loss: 0.0024
Epoch 127/200
0s - loss: 0.0026 - val_loss: 0.0025
Epoch 128/200
0s - loss: 0.0025 - val_loss: 0.0024
Epoch 129/200
0s - loss: 0.0025 - val_loss: 0.0024
Epoch 130/200
0s - loss: 0.0025 - val_loss: 0.0023
Epoch 131/200
0s - loss: 0.0024 - val_loss: 0.0026
Epoch 132/200
0s - loss: 0.0024 - val_loss: 0.0028
Epoch 133/200
0s - loss: 0.0025 - val_loss: 0.0023
Epoch 134/200
0s - loss: 0.0024 - val_loss: 0.0024
Epoch 135/200
0s - loss: 0.0024 - val_loss: 0.0028
Epoch 136/200
0s - loss: 0.0024 - val_loss: 0.0025
Epoch 137/200
0s - loss: 0.0023 - val_loss: 0.0024
Epoch 138/200
0s - loss: 0.0024 - val_loss: 0.0023
Epoch 139/200
0s - loss: 0.0023 - val_loss: 0.0024
Epoch 140/200
0s - loss: 0.0023 - val_loss: 0.0023
Epoch 141/200
0s - loss: 0.0024 - val_loss: 0.0023
Epoch 142/200
0s - loss: 0.0023 - val_loss: 0.0025
Epoch 143/200
0s - loss: 0.0023 - val_loss: 0.0023
Epoch 144/200
0s - loss: 0.0023 - val_loss: 0.0023
Epoch 145/200
0s - loss: 0.0023 - val_loss: 0.0024
Epoch 146/200
0s - loss: 0.0023 - val_loss: 0.0022
Epoch 147/200
0s - loss: 0.0022 - val_loss: 0.0022
Epoch 148/200
0s - loss: 0.0022 - val_loss: 0.0023
Epoch 149/200
0s - loss: 0.0023 - val_loss: 0.0021
Epoch 150/200
0s - loss: 0.0022 - val_loss: 0.0021
Epoch 151/200
0s - loss: 0.0021 - val_loss: 0.0025
Epoch 152/200
0s - loss: 0.0022 - val_loss: 0.0021
Epoch 153/200
0s - loss: 0.0022 - val_loss: 0.0021
Epoch 154/200
0s - loss: 0.0022 - val_loss: 0.0025
Epoch 155/200
0s - loss: 0.0022 - val_loss: 0.0023
Epoch 156/200
0s - loss: 0.0021 - val_loss: 0.0022
Epoch 157/200
0s - loss: 0.0021 - val_loss: 0.0023
Epoch 158/200
0s - loss: 0.0022 - val_loss: 0.0022
Epoch 159/200
0s - loss: 0.0021 - val_loss: 0.0020
Epoch 160/200
0s - loss: 0.0021 - val_loss: 0.0022
Epoch 161/200
0s - loss: 0.0021 - val_loss: 0.0021
Epoch 162/200
0s - loss: 0.0021 - val_loss: 0.0021
Epoch 163/200
0s - loss: 0.0020 - val_loss: 0.0022
Epoch 164/200
0s - loss: 0.0020 - val_loss: 0.0020
Epoch 165/200
0s - loss: 0.0020 - val_loss: 0.0021
Epoch 166/200
0s - loss: 0.0021 - val_loss: 0.0020
Epoch 167/200
0s - loss: 0.0020 - val_loss: 0.0023
Epoch 168/200
0s - loss: 0.0020 - val_loss: 0.0021
Epoch 169/200
0s - loss: 0.0020 - val_loss: 0.0024
Epoch 170/200
0s - loss: 0.0020 - val_loss: 0.0021
Epoch 171/200
0s - loss: 0.0019 - val_loss: 0.0020
Epoch 172/200
0s - loss: 0.0020 - val_loss: 0.0021
Epoch 173/200
0s - loss: 0.0019 - val_loss: 0.0020
Epoch 174/200
0s - loss: 0.0020 - val_loss: 0.0024
Epoch 175/200
0s - loss: 0.0020 - val_loss: 0.0020
Epoch 176/200
0s - loss: 0.0020 - val_loss: 0.0021
Epoch 177/200
0s - loss: 0.0019 - val_loss: 0.0020
Epoch 178/200
0s - loss: 0.0019 - val_loss: 0.0020
Epoch 179/200
0s - loss: 0.0019 - val_loss: 0.0022
Epoch 180/200
0s - loss: 0.0019 - val_loss: 0.0020
Epoch 181/200
0s - loss: 0.0019 - val_loss: 0.0021
Epoch 182/200
0s - loss: 0.0019 - val_loss: 0.0019
Epoch 183/200
0s - loss: 0.0019 - val_loss: 0.0019
Epoch 184/200
0s - loss: 0.0018 - val_loss: 0.0021
Epoch 185/200
0s - loss: 0.0018 - val_loss: 0.0019
Epoch 186/200
0s - loss: 0.0018 - val_loss: 0.0022
Epoch 187/200
0s - loss: 0.0019 - val_loss: 0.0021
Epoch 188/200
0s - loss: 0.0018 - val_loss: 0.0019
Epoch 189/200
0s - loss: 0.0018 - val_loss: 0.0019
Epoch 190/200
0s - loss: 0.0018 - val_loss: 0.0019
Epoch 191/200
0s - loss: 0.0018 - val_loss: 0.0021
Epoch 192/200
0s - loss: 0.0018 - val_loss: 0.0021
Epoch 193/200
0s - loss: 0.0018 - val_loss: 0.0020
Epoch 194/200
0s - loss: 0.0017 - val_loss: 0.0021
Epoch 195/200
0s - loss: 0.0017 - val_loss: 0.0023
Epoch 196/200
0s - loss: 0.0018 - val_loss: 0.0018
Epoch 197/200
0s - loss: 0.0017 - val_loss: 0.0020
Epoch 198/200
0s - loss: 0.0017 - val_loss: 0.0020
Epoch 199/200
0s - loss: 0.0017 - val_loss: 0.0020
Epoch 200/200
0s - loss: 0.0017 - val_loss: 0.0019
In [57]:
## TODO: Visualize the training and validation loss of your neural network
_, (ax1, ax2) = plt.subplots(1,2,figsize=(24,8))

ax1.plot(hist.epoch, hist.history['loss'],'r')
ax1.plot(hist.epoch, hist.history['val_loss'],'b')
ax1.set_title('Full 200 epochs')
ax1.legend(['Training loss','Validation loss'])
ax1.set_xlabel('Epoch');ax1.set_ylabel('RMS Loss')

k_epoch = 50
ax2.plot(hist.epoch[:k_epoch+1], hist.history['loss'][:k_epoch+1],'r')
ax2.plot(hist.epoch[:k_epoch+1], hist.history['val_loss'][:k_epoch+1],'b')
ax2.set_title('First %d epochs' %k_epoch)
ax2.legend(['Training loss','Validation loss'])
ax2.set_xlabel('Epoch');ax2.set_ylabel('RMS Loss')
plt.show()

Step 7: Visualize the Loss and Test Predictions

(IMPLEMENTATION) Answer a few questions and visualize the loss

Question 1: Outline the steps you took to get to your final neural network architecture and your reasoning at each step.

Answer: We don't need a long CNN for this as the task is relatively simple. I implemented a simple Convolution → Relu Activation → Max pool, similar to a VGG architecture. In the last layer, I add a global average pool instead of a max pool, then the feature vector goes through a dropout layer before the final FC output layer. Similar to VGG, I kept the 3d convolution filters small---2x2 or 3x3.

Few parameters are important here: number of layers, number of convolution filters, and dropout rate. I ran a grid search on these three parameters, running it for 50 epochs each. In hindsight, this was way too much, and I should've chosen a much smaller value (<=20).

The final parameters were chosen from the model with the best validation loss. I also saved another smaller model that had similar performance.

Question 2: Defend your choice of optimizer. Which optimizers did you test, and how did you determine which worked best?

Answer: I tested all 7 for a 30 epochs for a set value of other parameters. Some converge much quicker than others, such as RMSProp, Adam, and Nadam. SGD appears to converge the slowest. RMSProp seems to do well!

Use the code cell below to plot the training and validation loss of your neural network. You may find this resource useful.

In [58]:
## TODO: Visualize the training and validation loss of your neural network
_, (ax1, ax2) = plt.subplots(1,2,figsize=(24,8))

ax1.plot(hist.epoch, hist.history['loss'],'r')
ax1.plot(hist.epoch, hist.history['val_loss'],'b')
ax1.set_title('Full 200 epochs')
ax1.legend(['Training loss','Validation loss'])
ax1.set_xlabel('Epoch');ax1.set_ylabel('RMS Loss')

k_epoch = 50
ax2.plot(hist.epoch[:k_epoch+1], hist.history['loss'][:k_epoch+1],'r')
ax2.plot(hist.epoch[:k_epoch+1], hist.history['val_loss'][:k_epoch+1],'b')
ax2.set_title('First %d epochs' %k_epoch)
ax2.legend(['Training loss','Validation loss'])
ax2.set_xlabel('Epoch');ax2.set_ylabel('RMS Loss')
plt.show()

Question 3: Do you notice any evidence of overfitting or underfitting in the above plot? If so, what steps have you taken to improve your model? Note that slight overfitting or underfitting will not hurt your chances of a successful submission, as long as you have attempted some solutions towards improving your model (such as regularization, dropout, increased/decreased number of layers, etc).

Answer: I don't see a significant evidence of overfitting of underfitting. Even after 200 epochs, the losses seem to still decrease slightly (very slowly), which may a sign of some underfitting. Also, changes in dropout did not affect the performance on my models too much, indicating I could have used a more complex model. I tested 6 layers, which did not give a significant boost in performance. For sake of time, I did not pursue additional layers, especially as the models were already doing pretty well.

Visualize a Subset of the Test Predictions

Execute the code cell below to visualize your model's predicted keypoints on a subset of the testing images.

In [59]:
# Load model from 'my_model.h5'
from keras.models import load_model
model = load_model('my_model_fast.h5')
In [63]:
y_test = model.predict(X_test)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_test[i], y_test[i], ax)

Step 8: Complete the pipeline

With the work you did in Sections 1 and 2 of this notebook, along with your freshly trained facial keypoint detector, you can now complete the full pipeline. That is given a color image containing a person or persons you can now

  • Detect the faces in this image automatically using OpenCV
  • Predict the facial keypoints in each face detected in the image
  • Paint predicted keypoints on each face detected

In this Subsection you will do just this!

(IMPLEMENTATION) Facial Keypoints Detector

Use the OpenCV face detection functionality you built in previous Sections to expand the functionality of your keypoints detector to color images with arbitrary size. Your function should perform the following steps

  1. Accept a color image.
  2. Convert the image to grayscale.
  3. Detect and crop the face contained in the image.
  4. Locate the facial keypoints in the cropped image.
  5. Overlay the facial keypoints in the original (color, uncropped) image.

Note: step 4 can be the trickiest because remember your convolutional network is only trained to detect facial keypoints in $96 \times 96$ grayscale images where each pixel was normalized to lie in the interval $[0,1]$, and remember that each facial keypoint was normalized during training to the interval $[-1,1]$. This means - practically speaking - to paint detected keypoints onto a test face you need to perform this same pre-processing to your candidate face - that is after detecting it you should resize it to $96 \times 96$ and normalize its values before feeding it into your facial keypoint detector. To be shown correctly on the original image the output keypoints from your detector then need to be shifted and re-normalized from the interval $[-1,1]$ to the width and height of your detected face.

When complete you should be able to produce example images like the one below

In [41]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# plot our image
fig = plt.figure(figsize = (9,9))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('image copy')
ax1.imshow(image)
Out[41]:
<matplotlib.image.AxesImage at 0x7f916526add8>
In [68]:
### TODO: Use the face detection code we saw in Section 1 with your trained conv-net 
## TODO : Paint the predicted keypoints on the test image

# Convert to grayscale & use OpenCV face classifier
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
classifier = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
faces = classifier.detectMultiScale(gray, 1.25, 6)

# Make image copy to make changes with labels
image_labels = np.copy(image)
fig = plt.figure(figsize=(9,9))
ax = fig.add_subplot(111, xticks=[], yticks=[])
for x, y, w, h in faces:
    cv2.rectangle(image_labels,(x,y), (x+w,y+h), (255,0,0), 2)
    
    face = gray[y:y+h,x:x+w]/255. #load cropped image of the face and scale pixel values to [0,1]
    face = cv2.resize(face, (96,96))
    features = model.predict(np.reshape(face,(1,96,96,1)))[0] # [0] is there because the output is list of lists (the model expects an input with multiple images)
    
    features[0::2] = (features[0::2] + 1) * w/2 + x # change [-1,1] output to actual x-coordinate
    features[1::2] = (features[1::2] + 1) * h/2 + y # change [-1,1] output to actual y-coordinate
    ax.scatter(features[0::2],features[1::2],marker='o',c='c',s=10)
ax.imshow(image_labels)
2 faces detected
Out[68]:
<matplotlib.image.AxesImage at 0x7f91c17c6240>

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add facial keypoint detection to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for keypoint detection and marking in the previous exercise and you should be good to go!

In [30]:
import cv2
import time 
import numpy as np
from keras.models import load_model

def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # keep video stream open
    while rval:
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.08, 8)
        for (x,y,w,h) in faces:
            cv2.rectangle(frame, (x,y), (x+w,y+h), [255,0,0], 3)
            face = cv2.resize(gray[y:y+h,x:x+w]/255., (96,96))
            features = model.predict(np.reshape(face,(1,96,96,1)))[0]
            feature_x = (features[0::2] + 1) * w/2 + x # change [-1,1] output to actual x-coordinate
            feature_y = (features[1::2] + 1) * h/2 + y # change [-1,1] output to actual y-coordinate
            for cx,cy in zip(feature_x,feature_y):
                cv2.circle(frame, (cx,cy), 2, [0,255,0], thickness=4)
        # plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # destroy windows
            cv2.destroyAllWindows()
            
            # hack from stack overflow for making sure window closes on osx --> https://stackoverflow.com/questions/6116564/destroywindow-does-not-close-window-on-mac-using-python-and-opencv
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # read next frame
        time.sleep(0.0)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()  
In [32]:
# Run your keypoint face painter
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
model = load_model('my_model_fast.h5')
laptop_camera_go()

(Optional) Further Directions - add a filter using facial keypoints

Using your freshly minted facial keypoint detector pipeline you can now do things like add fun filters to a person's face automatically. In this optional exercise you can play around with adding sunglasses automatically to each individual's face in an image as shown in a demonstration image below.

To produce this effect an image of a pair of sunglasses shown in the Python cell below.

In [64]:
# Load in sunglasses image - note the usage of the special option
# cv2.IMREAD_UNCHANGED, this option is used because the sunglasses 
# image has a 4th channel that allows us to control how transparent each pixel in the image is
sunglasses = cv2.imread("images/sunglasses_4.png", cv2.IMREAD_UNCHANGED)

# Plot the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.imshow(sunglasses)
ax1.axis('off');

This image is placed over each individual's face using the detected eye points to determine the location of the sunglasses, and eyebrow points to determine the size that the sunglasses should be for each person (one could also use the nose point to determine this).

Notice that this image actually has 4 channels, not just 3.

In [65]:
# Print out the shape of the sunglasses image
print ('The sunglasses image has shape: ' + str(np.shape(sunglasses)))
The sunglasses image has shape: (1123, 3064, 4)

It has the usual red, blue, and green channels any color image has, with the 4th channel representing the transparency level of each pixel in the image. Here's how the transparency channel works: the lower the value, the more transparent the pixel will become. The lower bound (completely transparent) is zero here, so any pixels set to 0 will not be seen.

This is how we can place this image of sunglasses on someone's face and still see the area around of their face where the sunglasses lie - because these pixels in the sunglasses image have been made completely transparent.

Lets check out the alpha channel of our sunglasses image in the next Python cell. Note because many of the pixels near the boundary are transparent we'll need to explicitly print out non-zero values if we want to see them.

In [66]:
# Print out the sunglasses transparency (alpha) channel
alpha_channel = sunglasses[:,:,3]
print ('the alpha channel here looks like')
print (alpha_channel)

# Just to double check that there are indeed non-zero values
# Let's find and print out every value greater than zero
values = np.where(alpha_channel != 0)
print ('\n the non-zero values of the alpha channel look like')
print (values)
the alpha channel here looks like
[[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 ..., 
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]

 the non-zero values of the alpha channel look like
(array([  17,   17,   17, ..., 1109, 1109, 1109]), array([ 687,  688,  689, ..., 2376, 2377, 2378]))

This means that when we place this sunglasses image on top of another image, we can use the transparency channel as a filter to tell us which pixels to overlay on a new image (only the non-transparent ones with values greater than zero).

One last thing: it's helpful to understand which keypoint belongs to the eyes, mouth, etc. So, in the image below, we also display the index of each facial keypoint directly on the image so that you can tell which keypoints are for the eyes, eyebrows, etc.

With this information, you're well on your way to completing this filtering task! See if you can place the sunglasses automatically on the individuals in the image loaded in / shown in the next Python cell.

In [67]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot the image
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[67]:
<matplotlib.image.AxesImage at 0x7f472c2d21d0>
In [69]:
## (Optional) TODO: Use the face detection code we saw in Section 1 with your trained conv-net to put
## sunglasses on the individuals in our test image

# Convert to grayscale & use OpenCV face classifier
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
classifier = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
faces = classifier.detectMultiScale(gray, 1.25, 6)

# Make image copy to make changes with labels
image_labels = np.copy(image)
fig = plt.figure(figsize=(9,9))
ax = fig.add_subplot(111, xticks=[], yticks=[])
for x, y, w, h in faces:
    face = gray[y:y+h,x:x+w]/255. #load cropped image of the face and scale pixel values to [0,1]
    face = cv2.resize(face, (96,96))
    # [0] is there because the output is list of lists (the model expects an input with multiple images)
    features = model.predict(np.reshape(face,(1,96,96,1)))[0]
    
    brow_rx, brow_lx, eye_rx, eye_lx = (1.3*features[[18,14,6,10]] + 1) * w/2 + x
    brow_ry, brow_ly, eye_ry, eye_ly, nose_y = (features[[19,15,7,11,21]] + 1) * h/2 + y
    
    xmin = min(brow_rx, eye_rx)
    xmax = max(brow_lx, eye_lx)
    ymin = min(brow_ly,brow_ry)
    ymax = nose_y
    
    extent = (xmax, xmin, ymax, ymin)
    ax.imshow(sunglasses, extent=extent, zorder=1)
ax.imshow(image_labels, zorder=0)
Out[69]:
<matplotlib.image.AxesImage at 0x7f472c210400>

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add the sunglasses filter to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for adding sunglasses to someone's face in the previous optional exercise and you should be good to go!

In [1]:
import cv2
import time 
from keras.models import load_model
import numpy as np

def detectCascadeFeature(grayImage, cascade):
    features = cascade.detectMultiScale(grayImage, 1.08, 8)
    return features

def detectFacialFeatures(face, model):
    features = model.predict(np.reshape(cv2.resize(face/255., (96,96)),(1,96,96,1)))[0]
    return features

def extentSunglasses(facialFeatures, anchor = (0,0,0,0)):
    x,y,w,h = anchor
    brow_rx, brow_lx, eye_rx, eye_lx = (1.3*facialFeatures[[18,14,6,10]] + 1) * w/2 + x
    brow_ry, brow_ly, eye_ry, eye_ly, nose_y = (facialFeatures[[19,15,7,11,21]] + 1) * h/2 + y
    
    xmin = np.int(min(brow_rx, eye_rx))
    xmax = np.int(max(brow_lx, eye_lx))
    ymin = np.int(min(brow_ly,brow_ry))
    ymax = np.int(nose_y)
    
    return (xmax, xmin, ymax, ymin)

def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
        width = np.int(vc.get(3))
        height = np.int(vc.get(4))
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        # 
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        faces = detectCascadeFeature(gray, face_cascade)
        for (x,y,w,h) in faces:
            features = detectFacialFeatures(gray[y:y+h,x:x+w], model)
            (xmax, xmin, ymax, ymin) = extentSunglasses(features,(x,y,w,h))
            sunglasses_image = cv2.resize(sunglasses, (xmax-xmin,ymax-ymin))
            mask = sunglasses_image[:,:,[3,3,3]]/255
            mask_inv = 1-mask
            frame[ymin:ymax,xmin:xmax] = (np.multiply(sunglasses_image[:,:,:3],mask) + 
                                        np.multiply(frame[ymin:ymax,xmin:xmax],mask_inv))
        
        # Plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.0)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
Using TensorFlow backend.
In [2]:
# Load facial landmark detector model
model = load_model('my_model_fast.h5')
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
sunglasses = cv2.imread("images/sunglasses_4.png", cv2.IMREAD_UNCHANGED)

# Run sunglasses painter
laptop_camera_go()